<?php

namespace app\services\sms;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use app\api\validate\user\RegisterValidates;
use crmeb\exceptions\ApiException;

class SmsService
{
    protected $AccessKeyId = 'LTAI5tDcRuH5yb9g1npKjoAE';
    protected $AccessKeySecret = 'qXgLkN7aiWz44COnNbp5xbqhtn0wcO';
    protected $sendMsg = '';

    public function __construct()
    {
        $this->AccessKeyId = config('sms')['stores']['aliyun']['aliyun_AccessKeyId'];
        $this->AccessKeySecret = config('sms')['stores']['aliyun']['aliyun_AccessKeySecret'];
        $this->sendMsg = config('sms')['sendMsg'];
    }

    public function send(string $phone, int $code)
    {
        // 验证手机号
        validate(RegisterValidates::class)->scene('code')->check(['phone' => $phone]);

        AlibabaCloud::accessKeyClient($this->AccessKeyId, $this->AccessKeySecret)->regionId('ap-southeast-1')->asGlobalClient();
        dd($this->AccessKeyId);
        try {
            $result = AlibabaCloud::rpcRequest()
                ->product('Dysmsapi')
                ->host('dysmsapi.ap-southeast-1.aliyuncs.com')
                ->version('2018-05-01')
                ->action('SendMessageToGlobe')//请求api接口名称
                ->method('POST')
                ->options([
                    'query' => [
                        "To" => "$phone",
                        "Message" => sprintf($this->sendMsg, $code),
                    ],
                ])
                ->request();

//            "ResponseCode" => "MOBILE_NUMBER_ILLEGAL"
//            "RequestId" => "B80BF8B6-696C-342B-BCC4-17F4520405E5"
//            "Segments" => "1"
//            "ResponseDescription" => "The mobile number format is invalid."
//            "To" => "1111"

//            "ResponseCode" => "OK"
//            "NumberDetail" => array:3 [
//                "Region" => ""
//                "Country" => ""
//                "Carrier" => ""
//            ]
//            "RequestId" => "5E2EE3CA-4187-3813-BDFB-714AAFE2520E"
//            "Segments" => "1"
//            "ResponseDescription" => "OK"
//            "To" => "18571640043"
//            "MessageId" => "541911691026214719"

            $result = \GuzzleHttp\json_decode($result);
            if ($result && $result->ResponseCode === 'OK') {
                return true;
            }

            throw new ApiException('【err】：' . $result->ResponseDescription);
        } catch (ClientException $e) {
            throw new ApiException('【err】：' . $e->getErrorMessage());
        } catch (ServerException $e) {
            throw new ApiException('【err】：' . $e->getErrorMessage());
        }
    }
}
